package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.xxx.xbutler.data.ContactMapper;
import io.xxx.xbutler.data.RobotContactMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.RobotContact;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 删除联系人好友结果回调
 *
 * <pre>
 * {
 *     "nType": 3004,
 *     "vcMerchantNo": "",
 *     "vcRobotWxId": "",
 *     "vcRobotSerialNo": "",
 *     "vcSerialNo": "",
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "Data": {
 *         "vcContactWxId": "",
 *         "vcContactSerialNo": ""
 *     }
 * }
 * </pre>
 */
@Slf4j
@Component
public class _3004Handler implements CallbackHandler {

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private ContactMapper contactMapper;

    @Resource
    private RobotContactMapper robotContactMapper;

    @Override
    public String name() {
        return "删除联系人好友结果回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 3004;
    }

    @Override
    public void handle(Callback callback) {
        JSONObject data = (JSONObject) callback.getData();
        String robotId = callback.getRobotId();
        String contactId = data.getString("vcContactWxId");

        LambdaQueryWrapper<RobotContact> wrapper = new LambdaQueryWrapper<RobotContact>()
                .eq(RobotContact::getRobotId, robotId)
                .eq(RobotContact::getContactId, contactId);

        transactionTemplate.executeWithoutResult(_ -> {
            contactMapper.deleteById(contactId);
            robotContactMapper.delete(wrapper);
        });
    }
}
